package com.baozun.listener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.baozun.model.TContact;
import com.baozun.model.TContactExample;
import com.baozun.model.TContactExample.Criteria;
import com.baozun.service.ContactService;
import com.baozun.util.CommonConst;

/**
 * 
 * @Title:
 * @Company:宝尊电子商务有限公司
 * @Author:万世极缘
 * @Since:2015-1-8
 * @Copyright:Copyright (c) 2015
 * @ModifyDate:2015-1-8
 * @Version:1.1.0
 */
public class InitContactMapListener implements ServletContextListener {

    private ServletContext context = null;
    private Map<String, TContact> contactMap = null;
    private List<TContact> contactList = null;

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        this.context = event.getServletContext();

        if (contactMap == null) {
            /**
             * listener不归spring管理，所以只能手工获取
             */
            WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
            ContactService contactService = (ContactService) wac.getBean("contactService");
            contactMap = new HashMap<String, TContact>();
            TContactExample record = new TContactExample();
            Criteria criteria = record.createCriteria();
            record.or(criteria);
            record.setOrderByClause(TContact.DT_CREATE_TIME + " DESC");
            contactList = contactService.getList(record);
            context.setAttribute(CommonConst.CONTEXT_CONTACT_LIST, contactList);
            for (TContact contact : contactList) {
                contactMap.put(contact.getStContactId(), contact);
            }
            context.setAttribute(CommonConst.CONTEXT_CONTACT_MAP, contactMap);
        }
    }

}
